package com.ruoyi.gis.geoserver.service;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.xml.XmlUtil;
import com.ruoyi.gis.geoserver.domain.GeoServerLayer;
import com.ruoyi.gis.geoserver.domain.GeoServerLayerGroup;
import com.ruoyi.gis.geoserver.domain.StoreFeature;
import it.geosolutions.geoserver.rest.HTTPUtils;
import it.geosolutions.geoserver.rest.decoder.RESTLayer;
import it.geosolutions.geoserver.rest.manager.GeoServerRESTAbstractManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;


public class GeoServerGwcRESTManager extends GeoServerRESTAbstractManager {
    private final Logger logger = LoggerFactory.getLogger(GeoServerGwcRESTManager.class);
    /**
     * Default constructor.
     * <p>
     * Indicates connection parameters to remote GeoServer instance.
     *
     * @param restURL  GeoServer REST API endpoint
     * @param username GeoServer REST API authorized username
     * @param password GeoServer REST API password for the former username
     */
    public GeoServerGwcRESTManager(URL restURL, String username, String password) throws IllegalArgumentException {
        super(restURL, username, password);
    }
    public GeoServerLayer getLayerConfig(String workspace, String name) throws UnsupportedEncodingException {
        String workspaceAndLayerName = workspace+":"+name;
        String url = HTTPUtils.append(gsBaseUrl,"/gwc/rest/layers/",URLEncoder.encode(workspaceAndLayerName, "utf-8"),".xml").toString();
        logger.info("getLayerConfig {}",url);
        String response = HTTPUtils.get(url, gsuser, gspass);
        if(StringUtils.isEmpty(response)){
            return null;
        }
        logger.info("getLayerConfig {}",response);
        return XmlUtil.parseObject(response,GeoServerLayer.class);
    }
    public GeoServerLayer getLayerConfig(String workspaceAndLayerName) throws UnsupportedEncodingException {
        String url = HTTPUtils.append(gsBaseUrl,"/gwc/rest/layers/",URLEncoder.encode(workspaceAndLayerName, "utf-8"),".xml").toString();
        logger.info("getLayerConfig {}",url);
        String response = HTTPUtils.get(url, gsuser, gspass);
        if(StringUtils.isEmpty(response)){
            return null;
        }
        logger.info("getLayerConfig {}",response);
        GeoServerLayer geoServerLayer = XmlUtil.parseObject(response, GeoServerLayer.class);
        geoServerLayer.setSourceUrl(url);
        return geoServerLayer;
    }
//    public void setLayerConfig(String workspace, String name,GeoLayerConfig config) {
//        String url = HTTPUtils.append(gsBaseUrl,"/gwc/rest/layers/",workspace,":",name,".json").toString();
//        String content = JSON.toJSONString(config);
//        String response = HTTPUtils.post(url, content,"application/json",gsuser, gspass);
//        if(response!=null){
//
//        }
//    }
    public void setLayerConfig(String workspace, String name,GeoServerLayer config) throws UnsupportedEncodingException {
        String workspaceAndLayerName = workspace+":"+name;
        String url = HTTPUtils.append(gsBaseUrl,"/gwc/rest/layers/",URLEncoder.encode(workspaceAndLayerName, "utf-8"),".xml").toString();
        String content = XmlUtil.toXml(config);
        String response = HTTPUtils.post(url, content,"application/xml",gsuser, gspass);
        if(response!=null){

        }
    }

    public RESTLayer getLayer(String workspace, String name) throws UnsupportedEncodingException {
        if (workspace == null || workspace.isEmpty())
            throw new IllegalArgumentException("Workspace may not be null");
        if (name == null || name.isEmpty())
            throw new IllegalArgumentException("Layername may not be null");
        String workspaceAndLayerName = workspace+":"+name;
        String url = HTTPUtils.append("/rest/layers/",URLEncoder.encode(workspaceAndLayerName, "utf-8"),".xml").toString();

        RESTLayer layer =  RESTLayer.build(load(url));
        return layer;
    }
    private String load(String url) {
//        LOGGER.info("Loading from REST path " + url);
        String response = HTTPUtils.get(gsBaseUrl + url, gsuser, gspass);
        return response;
    }
    ///////////////////////////////////////////////////////
    //获取图层组图层
    public GeoServerLayerGroup getLayerGroupConfig(String layerGroup){
        String url = HTTPUtils.append(gsBaseUrl,"/rest/layergroups/",layerGroup,".xml").toString();
        logger.info("getLayerGroupConfig {}",url);
        String response = HTTPUtils.get(url, gsuser, gspass);
        if(StringUtils.isEmpty(response)){
            return null;
        }
        logger.info("getLayerGroupConfig {}",response);
        GeoServerLayerGroup geoServerLayerGroup = XmlUtil.parseObject(response, GeoServerLayerGroup.class);
        geoServerLayerGroup.setSourceUrl(url);
        return geoServerLayerGroup;
    }

    public StoreFeature getDataStoreFeatureTypes(String worksapce, String store){
        ///rest/workspaces/iot/datastores/iot/featuretypes.xml
        String url = HTTPUtils.append(gsBaseUrl,"/rest/workspaces/",worksapce,"/datastores/",store,"/featuretypes.json").toString();
        logger.info("getLayerGroupConfig {}",url);
        String response = HTTPUtils.get(url, gsuser, gspass);
        if(StringUtils.isEmpty(response)){
            return null;
        }
        logger.info("getDataStoreFeatureTypes {}",response);
        StoreFeature geoServerLayerGroup = JSON.parseObject(response, StoreFeature.class);//XmlUtil.parseObject(response, StoreFeatureTypes.class);
        return geoServerLayerGroup;
    }

}
